# coding=utf-8
# This is a sample Python script.

import os
import time

import requests

"""
@:key 系统通知
@:param title 通知标题
@:param text 通知文字
"""


def notify(title, text):
    if os.uname()[0].lower() == 'darwin':
        # Mac系统发系统提示音
        for i in range(1, 30):
            os.system("""
            afplay /System/Library/Sounds/Glass.aiff
            """)
        os.system("""
              osascript -e 'display notification "{}" with title "{}"'
              """.format(text, title))
    elif os.uname()[0].lower() == 'windows':
        # TODO 完善Windows系统通知和提示
        os.system("""
            {} {}
            """.format(text, title))
    else:
        print('不支持的操作系统')


"""
@:key 开启监控
@:param url 监控网址链接
@:param seconds 间隔频率秒数
"""


def start_monitor(url, seconds):
    while True:
        try:
            r = requests.get(url, auth=('user', 'pass'))
            print("%s status code %d [%s]" % (url, r.status_code, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
            if r.status_code != 200:
                info = '{}出现502[{}]'.format(url, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                print(info)
                # 发现异常桌面系统发通知
                notify('网站502', info)
            else:
                info = '{}正常[{}]'.format(url, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                print(info)
                # notify('网站{}'.format(r.status_code), info)
        except:
            print("[%s] 服务器请求异常" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            notify('监控不到服务器状态', "服务器请求异常")

        time.sleep(seconds)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    start_monitor('http://www.anline.cn', 15 * 60)  # 15 分钟监控
